/*
 * Copyright 2016 jeasonlzy(廖子尧)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mingtu.guards.callback;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.view.Window;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.EncodeUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.request.base.Request;
import com.mingtu.common.activity.LoginActivity;
import com.mingtu.common.base.BaseActivity;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.SPTools;
import com.mingtu.common.view.LoadingDialog;
import com.mingtu.common.view.MyDialog;
import com.mingtu.guards.activity.MainActivity;
import com.mingtu.guards.utils.MyConstant;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.ups.JPushUPSManager;
import okhttp3.Response;

/**
 * ================================================
 * 版    本：1.0
 * 修订历史：
 * ================================================
 */
public abstract class MyStringDialogCallback extends StringCallback {

    private LoadingDialog dialog;
    private String baseUrl;
    private static int num = 0;
    private Activity activity;
    private static Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 401:
                    num += 1;
                    BaseActivity baseActivity = (BaseActivity) ActivityUtil.getTopActivity();
                    MyDialog myDialog = null;
                    try {
                        myDialog = baseActivity.getLogoutDialog();
                        if (myDialog == null) { //防止重复的创建dialog
                            baseActivity.showLogoutDialog(handler);

                            JPushInterface.deleteAlias(ActivityUtils.getTopActivity(), Constant.TYPE_BIND_ALIAS);
                            JPushUPSManager.turnOffPush(ActivityUtils.getTopActivity(),null);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    break;
                default:
                    break;
            }
        }
    };
    private String token;

    public MyStringDialogCallback(Activity activity) {
        this.activity = activity;
        try {
            activity.runOnUiThread(new Runnable() {
                public void run() {
                    if(dialog == null){
                        dialog = new LoadingDialog(activity);
                        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                        dialog.setCanceledOnTouchOutside(false);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onStart(Request<String, ? extends Request> request) {
        token = SPStaticUtils.getString(SPTools.token);
        baseUrl = request.getBaseUrl();
        if (!StringUtils.isEmpty(token)) {
            if (!baseUrl.equals(Constant.getInstance().POST_LOGIN) &&
                    !baseUrl.equals(Constant.getInstance().POST_ADD_TRACK_SERVICE) &&
                    !baseUrl.equals(Constant.getInstance().GET_TRACK_SERVIC_LIST) &&
                    !baseUrl.equals(MyConstant.TIM_ONLINE_STATUS) &&
                    !baseUrl.equals(MyConstant.JPUSH_SERVER) &&
                    !baseUrl.equals(Constant.getInstance().POST_TRACK_SERVIC_DELETE)) {
                request.headers("token", token);
            }
        }

        if (this.baseUrl.contains("jpush.cn")) {
            String appkey = "0beef53d6694b5f1866cc6c3";
            String masterSecret = "ff8e7a269e6eca386274a9ad";
            String authorization = appkey + ":" + masterSecret;
            request.headers("Authorization", "Basic " + EncodeUtils.base64Encode2String(authorization.getBytes()));
        }

        if (dialog != null &&
                !dialog.isShowing() &&
                !baseUrl.equals(Constant.getInstance().POST_UPLOAD_LOCATION) &&
                !baseUrl.equals(Constant.getInstance().GET_UPDATE) &&
                !baseUrl.equals(Constant.getInstance().POST_DEVICE_LIST) &&
                !baseUrl.equals(Constant.getInstance().POST_ANIMAl_OCR) &&
                !baseUrl.equals(Constant.getInstance().POST_UPLOAD_TASK) &&
                !baseUrl.equals(MyConstant.POST_AIR_BASEINFO) &&
                !baseUrl.equals(MyConstant.POST_AIR_LAST_LOCATION) &&
                !baseUrl.equals(MyConstant.GET_ERROR_LOG) &&
                !baseUrl.equals(MyConstant.POST_MESSAGE_COUNT) &&
                !baseUrl.equals(MyConstant.POST_INDEX_REMIND_COUNT) &&
                !baseUrl.equals(MyConstant.POST_MY_MESSAGE_LIST) &&
                !baseUrl.equals(Constant.getInstance().POST_PLANT_OCR)) {

            try {
                if(activity != null && !(activity instanceof MainActivity)){
                    dialog.show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onFinish() {
        if (dialog != null && dialog.isShowing()) {
            try {
                dialog.dismiss();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public String convertResponse(Response response) throws Throwable {
        int responseCode = response.code();
        if (responseCode == 400) {
            return null;
        }
        String result = super.convertResponse(response);
        JSONObject jsonObject = JSON.parseObject(result);
        if (baseUrl.equals(MyConstant.GET_AREA) || baseUrl.equals(MyConstant.TIM_ONLINE_STATUS) || baseUrl.equals(MyConstant.JPUSH_SERVER)) {
            return result;
        } else {
            int code = Integer.parseInt(jsonObject.getString("code"));
            String msg = jsonObject.getString("msg");
            if (code == 0) {
                if (!StringUtils.isEmpty(result)) {
                    return result;
                } else {
                    ToastUtils.showLong(msg);
                    return null;
                }
            } else if (code == 401) {//token过期,重新登录
                //token 为空的时候，也会出现401的情况，这个时候不应该弹出异地登录的dialog
                if (StringUtils.isEmpty(token)) {
                    if (!(activity instanceof LoginActivity)) { //为了防止在登录界面的时候再次创建登录界面
                        if (!SPStaticUtils.contains(SPTools.token)) {
                            ToastUtils.showLong("请先进行登录操作！");
                        }
                        IntentUtils.getInstance().readyGo(ActivityUtil.getTopActivity(), LoginActivity.class);
//                        ARouter.getInstance()
//                                .build("/app/LoginActivity")
//                                .navigation();

                        ActivityUtil.removeAllActivity();
                    }
                } else {
                    //上报的接口出现401 就不执行此方法了
                    if (!baseUrl.equals(Constant.getInstance().POST_UPLOAD_LOCATION)) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Message msg = Message.obtain();
                                msg.what = 401;
                                handler.sendMessage(msg);
                            }
                        }).start();
                    }
                }

                return null;
            } else if (code == 500) {
                ToastUtils.showLong(msg);
                return null;
            } else {
                ToastUtils.showLong(result);
                return null;
            }
        }

    }
}
